package com.xzjt.web.config;


import cn.hutool.json.JSONObject;
import com.xzjt.common.components.JwtToken;
import com.xzjt.common.components.RedisService;
import com.xzjt.web.entity.SysMenu;
import com.xzjt.web.entity.SysRole;
import com.xzjt.web.entity.SysUser;
import com.xzjt.web.exception.InvalidTokenException;
import com.xzjt.web.service.AuthcService;
import com.xzjt.web.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;

import static java.util.stream.Collectors.toSet;


/**
 * @ClassName: UserRealm
 * @Author: yuandong
 * @Date 2021/10/8 14:04
 */
@Component
@Slf4j
public class UserRealm extends AuthorizingRealm {


    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private JwtService jwtService;

    @Autowired
    private RedisService redisService;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 认证方法  默认使用此方法进行用户名正确与否验证，错误抛出异常即可
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String token = authenticationToken.getCredentials().toString();

        String username = jwtService.getUsername(token);

        SysUser user= this.sysUserService.selectByUsername(username);


        if (username == null) {
            throw new AuthenticationException("token无效，请重新登录！");
        }


        // 先校验缓存中Token是否存在，缓存中不存在Token说明Token已失效，需要重新登录
        SysUser sysUser =(SysUser)  redisService.get(token);
        if (sysUser==null) {
            //token过期
            throw new AuthenticationException("token已过期，请重新登录！");
        }


        if (! jwtService.verify(token, username)) {
            throw new AuthenticationException("token认证失败！");
        }


        //更新token的有效期
        long tokenExpireTime = 60 ;
        redisService.expire(token,tokenExpireTime); //单位是分钟


        return new SimpleAuthenticationInfo(username, token, getName());
    }



    /**
     * 授权方法  有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        // 获取从认证过程保留的 user 对象
        String username =(String) principals.getPrimaryPrincipal();

        //**获取用户
        SysUser user = this.sysUserService.getByUserName(username);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        //**用户角色
        Set<String> roles = user.getRoles().stream().map(SysRole::getRoleCode).collect(toSet());
        authorizationInfo.addRoles(roles);

        //**用户权限
        Set<String> menus = user.getRoles().stream().map(SysRole::getMenus).flatMap(List::stream).map(SysMenu::getMenuCode).collect(toSet());
        authorizationInfo.addStringPermissions(menus);

        return authorizationInfo;

    }

    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

}
